<?php

class Mac_Image_Helper
{
    public static function resize ($src, $dest, $new_width, $new_height, $keepratio=true, $newname=null)
    {
        // TODO : gérer les erreurs
        $dest = (substr($dest, -1)=='/') ? substr($dest, 0, -1) : $dest;
        if (!is_dir($dest)) {
            // error
            return false;
        }
        
        $pathinfo = pathinfo($src);
        
        $imgdata = getimagesize($src);
        $imgwidth = $imgdata[0];
        $imgheight = $imgdata[1];
        $imgmime = $imgdata['mime'];
        
        if ($keepratio === true) {
            $ratio_width = $new_width/$imgwidth;
            $ratio_height = $new_height/$imgheight;
            
            $final_width = floor(($ratio_width <= $ratio_height) ? $imgwidth*$ratio_width : $imgwidth*$ratio_height);
            $final_height = floor(($ratio_height <= $ratio_width) ? $imgheight*$ratio_height : $imgheight*$ratio_width);
        } else {
            $final_width = $new_width;
            $final_height = $new_height;
        }
        
        if ($imgmime === 'image/jpeg') {
            $img_src = imagecreatefromjpeg($src);
        } else if ($imgmime === 'image/gif') {
            $img_src = imagecreatefromgif($src);
        } else if ($imgmime === 'image/png') {
            $img_src = imagecreatefrompng($src);
        }
        
        $img_dst = imagecreatetruecolor($final_width, $final_height);
        
        imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $final_width, $final_height, $imgwidth, $imgheight);
        
        if ($newname === null) {
            $renamed = $pathinfo['filename'].'.png';
        } else {
            $renamed = $newname;
        }
        
        imagepng($img_dst, $dest.'/'.$renamed);
        return $renamed;
    }
}